package com.ktjiaoyu.travelaiagent.tools;

import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.ai.chat.model.ToolContext;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class WebScrapingTool {

    /**
     * 读取网页内容，提取HTML中的关键文本内容
     *
     * @param url 网页URL地址
     * @return 网页的关键文本内容
     */
    @Tool(description = "Read the content of a web page and extract key text content.")
    public String scrapeWebContent(@ToolParam(description = "The URL of the web page to scrape.", required = true) String url,
                                   ToolContext toolContext) {
        log.info("AI调用scrapeWebContent工具读取网页内容，URL: {}", url);
        
        try {
            // 使用Jsoup连接到指定URL并获取文档对象
            // 设置超时时间为10秒，忽略内容类型检查
            // 添加常见的浏览器请求头来模拟真实浏览器访问，避免反爬虫机制
            Document document = Jsoup.connect(url)
                    .timeout(10000)
                    .ignoreContentType(true)
                    .userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
                    .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8")
                    .header("Accept-Language", "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7")
                    .header("Accept-Encoding", "gzip, deflate, br")
                    .header("Connection", "keep-alive")
                    .header("Upgrade-Insecure-Requests", "1")
                    .get();
            
            // 提取网页标题
            String title = document.title();
            
            // 提取网页正文文本内容（自动忽略script和style标签）
            String bodyText = document.body().text();
            
            // 组合标题和正文内容返回
            StringBuilder result = new StringBuilder();
            if (!title.isEmpty()) {
                result.append("网页标题: ").append(title).append("\n\n");
            }
            result.append("网页内容: ").append(bodyText);
            
            log.info("AI调用scrapeWebContent工具读取网页内容成功，URL: {}", url);
            return result.toString();
        } catch (IOException e) {
            log.error("AI调用scrapeWebContent工具读取网页内容出现异常，URL: {}, 错误信息: {}", url, e.getMessage());
            return "读取网页内容时发生错误: " + e.getMessage();
        } catch (Exception e) {
            log.error("AI调用scrapeWebContent工具读取网页内容出现未知异常，URL: {}, 错误信息: {}", url, e.getMessage());
            return "读取网页内容时发生未知错误: " + e.getMessage();
        }
    }
}